<?php

namespace Gateway;

use Cassandra\Timeuuid;
use Exception;

/**
 * 请求阿里云网关
 */
class ESAliyunGateway
{
    private  $appCode ;
    /**
     * 实例化
     * @param appCode 获取 appCode,参考 : https://esandinfo.yuque.com/yv6e1k/ulp2ub/fs2mm48opwox3xc4?singleDoc#
     */
    public function __construct($appCode) {
        $this->appCode = $appCode;
    }
    /**
     * @param $url           阿里云的URL地址
     * @param $bizContent    业务数据
     * @return string
     */
    public function sendToGateWay($url, $bizContent){
        $response = new GatewayResponse();
        $rspBody = null;
        try{
            do{
                //对传入参数进行判断
                if($url ==null || $bizContent == null){
                    $response->initWithCode("-1", "无效传入参数");
                    break;
                }
                // 发送请求到网关
                $body = json_decode($bizContent, true);
                $request = new HttpRequest($url, "", HttpMethod::POST, "", "");
                $request->setHeader("Authorization","APPCODE ".$this->appCode);
                //设定Content-Type，根据服务器端接受的值来设置
                $request->setHeader(HttpHeader::HTTP_HEADER_CONTENT_TYPE, ContentType::CONTENT_TYPE_FORM);
                $request->setHeader(SystemHeader::X_CA_NONCE,uniqid());
                //设定Accept，根据服务器端接受的值来设置
                $request->setHeader(HttpHeader::HTTP_HEADER_ACCEPT, ContentType::CONTENT_TYPE_FORM);
                $formattedBody = http_build_query($body);
                $request->setBodyString( $formattedBody);
                $httpResponse = HttpClient::execute($request);
                $statusCode = $httpResponse->httpStatusCode;
                if ($statusCode != '200') {
                    LOG::ERROR("服务器处理异常, 状态码 : ". $statusCode);
                    $response->initWithCode("-1", "服务处理异常");
                }
                $rspBody = $httpResponse->getBody();
                LOG::DEBUG("服务器返回 body 数据: " . $rspBody);
                $headers = $httpResponse->header;
                $json_head =json_encode($headers);
                LOG::DEBUG("服务器返回head数据：". $json_head);

            }while(false);
        }catch (Exception $e){
            LOG::ERROR("发生异常: " . $e);
            $response->initWithCode("-1", "发生异常 : " . $e->getMessage());
        }
        return $rspBody;
    }


}
